package me.huha.factory;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import me.huha.entity.IpMessageEntity;
import me.huha.service.api.IpCityApiService;
import me.huha.service.api.impl.SinaIpCityImpl;
import me.huha.service.api.impl.TaoIpCityImpl;
import me.huha.service.api.impl.WhoisIpCityImpl;
/**
 *	     类名: IpApiFactory.java
 *    描述: ip网络api工厂
 *    作者: Yepx
 * 创建日期: 2017年2月14日 上午9:10:59
 */
public class IpApiFactory {
	
	private static Logger logger = Logger.getLogger(IpApiFactory.class);
	private static int arrayIndex = 0; //ip 公网 Api 的实体类 list 的下标
	private static List<Class<?>> classList = new ArrayList<Class<?>>();
    
	/**
	 * 静态加载  ip公网 Api 的实体类
	 */
	static {
		classList.add(WhoisIpCityImpl.class);
		classList.add(TaoIpCityImpl.class);
		classList.add(SinaIpCityImpl.class);
    }

    
	public static IpMessageEntity getIpMessage(String ip){
		
		IpCityApiService ipCityApiService = IpApiFactory.createIpCityApiService(classList.get(arrayIndex));
		IpMessageEntity ipMessageEntity = null;
		ipMessageEntity = ipCityApiService.getAddresses(ip);
		
		//请求数据为不空，或者已经过了一轮请求，则跳出循环。 
		while (ipMessageEntity == null && arrayIndex < classList.size()) {
			
			logger.info("================="+classList.get(arrayIndex).getName()+"=================");
			arrayIndex = arrayIndex + 1;
			if(arrayIndex >= classList.size()){
				break;
			}
			ipMessageEntity = getIpMessage(ip);
			
			if(ipMessageEntity != null){
				break;
			}
		}
		
		return ipMessageEntity;
		
	}
	
	/**
     * 创建ip 公网 Api 的实体类
	 * @param clazz
	 * @return
	 */
	public static IpCityApiService createIpCityApiService(Class<?> clazz){
		
		IpCityApiService ipCityApiService = null;
		try {
			ipCityApiService = (IpCityApiService) Class.forName(clazz.getName()).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ipCityApiService;
	}
}
